package co.yixiang.message.redis.config;

import cn.hutool.core.util.StrUtil;
import co.yixiang.message.redis.listener.RedisKeyExpirationListener;
import co.yixiang.modules.activity.service.YxStorePinkService;
import co.yixiang.modules.order.service.YxStoreOrderService;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

/**
 * Redis监听配置类
 * 用于配置Redis键过期事件的监听
 */
@Configuration(proxyBeanMethods = false)
@AllArgsConstructor
public class RedisListenerConfig {

    // Redis模板，用于操作Redis数据库
    private final RedisTemplate<String, String> redisTemplate;
    // Redis配置属性，包含数据库索引等信息
    private final RedisConfigProperties redisConfigProperties;
    // 订单服务，处理与订单相关的业务逻辑
    private final YxStoreOrderService storeOrderService;
    // 拼团服务，处理与拼团相关的业务逻辑
    private final YxStorePinkService storePinkService;

    /**
     * 创建并配置Redis消息监听容器
     *
     * @param factory Redis连接工厂，用于创建与Redis服务器的连接
     * @return 配置好的Redis消息监听容器
     */
    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory factory) {
        // 构造Redis键过期事件的通道名称
        String topic =StrUtil.format("__keyevent@{}__:expired", redisConfigProperties.getDatabase());
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(factory);
        // 添加消息监听器和对应的通道
        container.addMessageListener(new RedisKeyExpirationListener(redisTemplate,redisConfigProperties
             ,storeOrderService,storePinkService), new PatternTopic(topic));
        return container;
    }
}
